package service;

import dao.WorkerDao;
import dao.impl.WorkerDaoImpl;
import org.apache.commons.beanutils.BeanUtils;
import pojo.Worker;
import util.LogUtil;
import util.MD5Util;
import util.Result;
import util.StringDataCheckUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;

public class SelfInfoService {

    private WorkerDao workerDao = new WorkerDaoImpl();

    /**
     * 个人信息密码修改
     * @param request
     * @param response
     */
    public void editSelfInfo(HttpServletRequest request, HttpServletResponse response) {
        try {
            Map<String, String[]> parameterMap = request.getParameterMap();
            Worker worker = new Worker();
            BeanUtils.populate(worker, parameterMap);
            Worker workerById = workerDao.findWorkerById(worker.getWorkerId().toString());
            String oldWorkerPassword = request.getParameter("oldWorkerPassword");
            if (!StringDataCheckUtil.check(oldWorkerPassword)) {
                Result.response(1002, "数据参数有误！", response);
                return;
            }
            if (!MD5Util.MD55(oldWorkerPassword).equals(workerById.getWorkerPassword())){
                Result.response(1001, "原密码错误！", response);
                return;
            }
            if (workerDao.updateWorkerPassword(worker.getWorkerId().toString(), MD5Util.MD55(worker.getWorkerPassword()))<=0) {
                Result.response(1003, "密码修改错误！", response);
                return;
            }
            LogUtil.addLog("编辑个人信息成功", request);
            Result.response(200, "修改成功！", response);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
    }
}
